package com.example.modules.user;

import cn.hutool.json.JSONObject;
import com.example.generator.mapper.UserMapper;
import com.example.generator.model.User;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
@AllArgsConstructor
public class UserService implements UserDetailsService {
    UserMapper userMapper;
    PasswordEncoder passwordEncoder;

    public List<User> userList() {
        return userMapper.selectAll();
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetailsVO user = userMapper.selectByUsernameFetchResource(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        return user;
    }

    @Transactional(rollbackFor = Exception.class)
    public void register(JSONObject param) {
        String username = param.getStr("username");
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("username", username);
        int i = userMapper.selectCountByExample(example);
        if (i > 0) {
            throw new RuntimeException("用户名已存在");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(param.getStr("password")));
        user.setEmail(param.getStr("email"));
        userMapper.insertSelective(user);
        userMapper.initUserRole(user.getId());
    }

    public UserDetailsVO modifyInfo(Integer userId, UserDetailsVO user) {
        User userOld = new User();
        userOld.setId(userId);
        userOld.setName(user.getName());
        userOld.setEmail(user.getEmail());
        userOld.setGender(user.getGender());
        userMapper.updateByPrimaryKeySelective(userOld);
        return userMapper.selectByIdFetchResource(userId);
    }

    public void forget(JSONObject jsonObject) {
        String email = jsonObject.getStr("email");
        String password = jsonObject.getStr("password");
        String username = jsonObject.getStr("username");
        if (ObjectUtils.isEmpty(username) || ObjectUtils.isEmpty(email) || ObjectUtils.isEmpty(password)) {
            throw new RuntimeException("信息填写错误");
        }
        UserDetailsVO user = userMapper.selectByUsernameFetchResource(username);

        if (user == null || !(email.equals(user.getEmail()))) {
            throw new RuntimeException("信息填写错误");
        }
        if (passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("密码不能和原密码相同");
        }
        user.setPassword(passwordEncoder.encode(password));
        user.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);
    }

    public void changePassword(JSONObject jsonObject, UserDetailsVO user) {
        String old = jsonObject.getStr("old");
        String password = jsonObject.getStr("new");
        if (ObjectUtils.isEmpty(old) || ObjectUtils.isEmpty(password)) {
            throw new RuntimeException("信息填写错误");
        }
        if (!passwordEncoder.matches(old, user.getPassword())) {
            throw new RuntimeException("原密码不正确");
        }
        if (passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("密码不能和原密码相同");
        }
        user.setPassword(passwordEncoder.encode(password));
        user.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);
    }
}
